package secondriver.springsubway.example.validator;

import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import secondriver.springsubway.example.bean.User;

/**
 * Spring自定义校验器
 */
public class UserValidator implements Validator {

	private static String userNameRegex = "[a-zA-Z0-9]{8,15}";
	private static String userPasswodRegex = "[a-zA-Z0-9]";

	@Override
	public boolean supports(Class<?> clazz) {
		return ClassUtils.isAssignable(clazz, User.class);
	}

	@Override
	public void validate(Object target, Errors errors) {
		User user = (User) target;
		if (null == user) {
			errors.reject("errorcodes.user.is.null", "User object is null.");
		}
		if (StringUtils.isEmpty(user.getUserName())) {
			errors.rejectValue("userName", "userName.not.null");
		} else if (user.getUserName().matches(userNameRegex)) {
			errors.rejectValue("userName", "userName.rules");
		}

	}

	public static void main(String[] args) {
		System.out.println("2aAsdg2rfg".matches(userPasswodRegex));
	}

}
